#include "reg.h"
#include "ui_reg.h"
#include <QPixmap>
#include <QPalette>
Reg::Reg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Reg)
{
    ui->setupUi(this);
    this->setWindowTitle("注册");
    QPixmap pixmap = QPixmap(":/img/bg2.jpg");
    QPixmap pix = pixmap.scaled(this->size());
    QPalette pal;
    pal.setBrush(QPalette::Background,QBrush(pix));
    this->setPalette(pal);
    db = Database::getInstance().getDatabase();
}

Reg::~Reg()
{
    delete ui;
}

void Reg::on_pushButton_reg_clicked()
{
    QString username = ui->lineEdit_name->text();
    QString password = ui->lineEdit_pwd->text();
    if(username.isEmpty() || password.isEmpty())
    {
        QMessageBox::warning(this,"注册","用户名或密码不能为空");
        return;
    }
    QByteArray hash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256);
    QString hashedPassword = hash.toHex();

    QSqlQuery query(db);
    query.prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    query.addBindValue(username);
    query.addBindValue(hashedPassword);

    if (query.exec()) {
        QMessageBox::information(this, "Success", "User registered successfully!");
        emit show_main();
        this->close();
    } else {
        QMessageBox::critical(this, "Error", query.lastError().text());
    }
}
